<template>
  <div id="captchaCode-dialog">
    <el-dialog
        v-model="captchaCodeShow"
        title="图灵码验证"
        width="500">
      <div class="captchaCode-dialog-content" style="padding: 2rem 0;height: 14rem">
        <div class="input-box">
          <div class="input">
            <el-input v-model="captchaCode" type="text" @keydown.enter="checkCode" @blur="checkCode"
                      clearable @focus="captchaCodeErrorShow = false"
                      placeholder="请输入右侧的图灵验证码"/>
          </div>
          <div class="code-image" @click="updateVerifyCode">
            <el-image :src="captchaPath" class="verifyCode"/>
          </div>
        </div>
        <div class="error-msg" v-show="captchaCodeErrorShow">
          {{ captchaCodeMsg }}
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {checkCaptchaCode} from "@/api/userApi.js";
import {successCode} from "@/api/base/http.js";
import * as myMessage from "@/utils/myMessage.js";

export default {
  props: {
    show: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      captchaCodeErrorShow: false,
      captchaPath: "",
      captchaCodeMsg: "验证码错误，请重试",
      captchaCode: "",
      captchaCodeShow: false,
      captchaCodeCheckIng: false,
      sendEmailLoading: false,
    }
  },
  watch: {
    "show": {
      handler(newVal) {
        this.updateVerifyCode();
        this.captchaCode = "";
        this.captchaCodeErrorShow = false;
        this.captchaCodeShow = true;
      }
    }
  },
  methods: {
    updateVerifyCode() {
      this.captchaPath = "/_api/user/utils/captcha_code?rm=" + Math.floor(Math.random() * 1000);
    },
    checkCode() {
      if (this.captchaCode === "") {
        return;
      }
      if (this.captchaCodeCheckIng) {
        return;
      }
      checkCaptchaCode(this.captchaCode).then(res => {
        if (res.code === successCode) {
          myMessage.success("验证成功");
          this.captchaCodeShow = false;
          this.$emit("captchaCodeCheckState", true);
        } else {
          this.$emit("captchaCodeCheckState", false);
          this.updateVerifyCode();
          this.captchaCodeErrorShow = true;
        }
      })
    },
  }
}
</script>
<style scoped lang="scss">
#captchaCode-dialog {
  .input-box {
    display: flex;
    align-items: center;
    padding: 1rem 0.5rem;

    .input {
      width: 25rem;
      margin-right: 2rem;
    }

    .error-msg {
      color: #d23d69;
    }

    .success-msg {
      color: #47d15d;
    }

    .warring-msg {
      color: rgb(230, 162, 60);
    }

    .verifyCode {
      width: 200px;
      height: 40px;
      cursor: pointer;
      border: solid 1px #ded3d9;
      user-select: none;
    }

    :deep(.code-image) {
      display: flex;
      align-items: center;
    }
  }
}
</style>